package com.amc.framework.interceptor;

import com.amc.common.annotation.RequestParamLog;
import com.amc.common.utils.RequestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * @author ZhangXX
 * 统一请求日志打印
 * @date @2022/1/7 15:27
 */
@RefreshScope
@Component
public class LogInfoInterceptor implements HandlerInterceptor {

    private static final Logger log = LoggerFactory.getLogger(LogInfoInterceptor.class);


    @Value("${print.requestLog:false}")
    private Boolean printRequestLog;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!printRequestLog) {
            return true;
        }
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            RequestParamLog annotation = method.getAnnotation(RequestParamLog.class);
            if (annotation != null) {
                String requestParams = "";
                try {
                    requestParams = RequestUtils.getRequestJsonString(request);
                } catch (Exception e) {
                    log.error("获取接口请求参数异常", e);
                }
                log.info("请求地址:【{}】 {},请求参数:{}", request.getMethod(), request.getRequestURI(), requestParams);
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object o, Exception e) throws Exception {

    }

}
